package com.xunwulian.web.controller.buss;

import com.alibaba.dubbo.config.annotation.Reference;
import com.google.gson.Gson;
import com.xunwulian.api.dto.BaseResponse;
import com.xunwulian.api.iface.*;
import com.xunwulian.base.constant.PkgType;
import com.xunwulian.base.constant.RoleType;
import com.xunwulian.base.dao.CardNodeDao;
import com.xunwulian.base.entity.AppEntity;
import com.xunwulian.base.entity.CardNodeEntity;
import com.xunwulian.base.entity.Page;
import com.xunwulian.base.entity.User;
import com.xunwulian.base.util.*;
import com.xunwulian.web.controller.BaseController;
import com.xunwulian.web.entity.CardNodeEntityWrapper;
import com.xunwulian.web.manager.CardNodeManager;
import com.xunwulian.web.util.AppUtil;
import com.xunwulian.web.util.Const;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping(value = "/cardnode")
public class CardNodeController extends BaseController {

    private MyLogUtil myLogUtil = new MyLogUtil(CardNodeController.class);

    private BeanUtil3 beanUtils = new BeanUtil3();

    private String menuUrl = "cardnode/list.do"; // 菜单地址(权限用)

    @Autowired
    private CardNodeManager manager;

    String appId = System.getenv("appId");
    String registryAddress = System.getenv("registry");

    @Reference
    private UserAPI userAPI;
    @Reference
    private AppAPI appAPI;
    @Reference
    private CardNodeAPI cardNodeAPI;
    @Reference
    private RoleAPI roleAPI;
    @Reference
    private ConfigAPI configAPI;

//    private UserAPI userAPI = new Consumer<UserAPI>().getApi(UserAPI.class, ConstantBean.XWL_GROUP, appId, registryAddress);
//    private AppAPI appAPI = new Consumer<AppAPI>().getApi(AppAPI.class, ConstantBean.XWL_GROUP, appId, registryAddress);
//    private CardNodeAPI cardNodeAPI = new Consumer<CardNodeAPI>().getApi(CardNodeAPI.class, ConstantBean.XWL_GROUP, appId, registryAddress);
//    private RoleAPI roleAPI = new Consumer<RoleAPI>().getApi(RoleAPI.class, ConstantBean.XWL_GROUP, appId, registryAddress);
//    private ConfigAPI configAPI = new Consumer<ConfigAPI>().getApi(ConfigAPI.class, ConstantBean.XWL_GROUP, appId, registryAddress);

    @Autowired
    private CardNodeDao cardNodeDao;

    /**
     * @return
     */
    @Transactional
    @RequestMapping(value = "/clear")
    public Object clear() {

        manager.clearAll();

        Map map = new HashMap();
        map.put("code", "0");
        map.put("msg", "Success");

        return AppUtil.returnObject(new PageData(), map);
    }

    /**
     * @return
     */
    @Transactional
    @RequestMapping(value = "/addNode")
    public Object addNode() {

        // 先清理
        manager.clearAll();

        // 生成新节点
        manager.addNewNode();

        Map map = new HashMap();
        map.put("code", "0");
        map.put("msg", "Success");

        return AppUtil.returnObject(new PageData(), map);
    }


    /**
     * 列表
     *
     * @param page
     * @return
     */
    @RequestMapping(value = "/list")
    public ModelAndView list(Page page, String msisdnKey, String userNameKey) {

        logBefore(logger, "列表CardNode");

        logger.info("page:" + new Gson().toJson(page));

        ModelAndView mv = this.getModelAndView();

        // 从session获取用户信息
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        // 管理员查询所有
        String userId = UserUtil.isAdmin(user.getROLE_ID()) || UserUtil.isSubAdmin(user.getROLE_ID()) ? "" : user.getUSER_ID();
        String appId = UserUtil.isSubAdmin(user.getROLE_ID()) ? user.getAppId() : "";

        BaseResponse response = cardNodeAPI.listPage(page, appId, userId, msisdnKey, userNameKey);
        List<CardNodeEntity> varList = (List<CardNodeEntity>) response.getData();
        page = response.getPage();

        // 用户类型
        int isAdmin = 0;
        RoleType roleType = roleAPI.getRoleTypeById(user.getROLE_ID());
        if (roleType.getType().equals(RoleType.ADMIN.getType())) {
            isAdmin = 1;
        }

        // 结果
        List<CardNodeEntityWrapper> listWrapper = varList.stream().map(entity -> new CardNodeEntityWrapper(entity)).collect(Collectors.toList());

        mv.addObject("varList", listWrapper);

        mv.setViewName("system/cardnode/cardnode_list");
        mv.addObject("msisdnKey", msisdnKey);
        mv.addObject("userNameKey", userNameKey);
        mv.addObject("isAdmin", isAdmin);
        mv.addObject("page", page);
        mv.addObject(Const.SESSION_QX, this.getHC()); // 按钮权限

        return mv;
    }

    /**
     * 去修改页面
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/goEdit")
    public ModelAndView goEdit(@RequestParam("id") long id) {
        logBefore(logger, "去修改CardNode界面");

        ModelAndView mv = this.getModelAndView();

        // 从session获取用户信息
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);

        String userId = UserUtil.isAdmin(user.getROLE_ID()) || UserUtil.isSubAdmin(user.getROLE_ID()) ? "" : user.getUSER_ID();
        String appId = UserUtil.isSubAdmin(user.getROLE_ID()) ? user.getAppId() : "";

        try {

            // 分配的用户列表
            List<User> userList = userAPI.listPage(null,
                    null,
                    appId,
                    userId).getData();

            //根据ID读取
            CardNodeEntity entity = cardNodeDao.getById(id);
            CardNodeEntityWrapper wrapper = new CardNodeEntityWrapper(entity);

            // 用户类型
            int isAdmin = 0;
            RoleType roleType = roleAPI.getRoleTypeById(user.getROLE_ID());
            if (roleType.getType().equals(RoleType.ADMIN.getType())) {
                isAdmin = 1;
            }

            mv.addObject("entity", wrapper);
            mv.addObject("user", user);
            mv.addObject("userList", userList);

            List<AppEntity> apps = appAPI.list(user.getROLE_ID(), user.getAppId());
            mv.addObject("appList", apps);
            myLogUtil.log(beanUtils.listToJson(apps));
            myLogUtil.log(appId);

            mv.addObject("pkgList", CollectionUtils.asList(PkgType.class.getEnumConstants()));
            mv.addObject("isAdmin", isAdmin);

            mv.setViewName("system/cardnode/cardnode_edit");
            mv.addObject("msg", "edit");


        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return mv;
    }

    /**
     * 修改
     *
     * @param id
     * @param authUserId
     * @param openDate
     * @param userOpenDate
     * @param appId
     * @param pkg
     * @param userPkg
     * @param userPrice
     * @return
     * @throws Exception
     */
    @Transactional
    @RequestMapping(value = "/edit")
    public ModelAndView edit(
            long id,
            String authUserId,
            Date openDate,
            Date userOpenDate,
            String appId,
            Integer pkg,
            Integer userPkg,
            Double userPrice,
            String start0,
            String start1,
            String end0,
            String end1) throws Exception {

        logBefore(logger, "修改CardNode");

        long start = Long.valueOf(start0 + start1);
        long end = Long.valueOf(end0 + end1);

        myLogUtil.log("start:" + start + ", end:" + end);

        ModelAndView mv = this.getModelAndView();

        User user = userAPI.getByUid(authUserId);

        manager.setUserId(
                id,
                start,
                end,
                authUserId,
                user.getUSERNAME(),
                openDate,
                userOpenDate,
                appId,
                pkg,
                userPkg,
                userPrice);

        mv.addObject("msg", "success");
        mv.setViewName("save_result");
        return mv;
    }

    /**
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/download")
    public void download(HttpServletResponse response, String msisdnKey, String userNameKey) {
        // 从session获取用户信息
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        User user = (User) session.getAttribute(Const.SESSION_USER);
        try {

            // 管理员查询所有
            String userId = UserUtil.isAdmin(user.getROLE_ID()) || UserUtil.isSubAdmin(user.getROLE_ID()) ? "" : user.getUSER_ID();
            String appId = UserUtil.isSubAdmin(user.getROLE_ID()) ? user.getAppId() : "";

            BaseResponse rpcResponse = cardNodeAPI.listPage(null, appId, userId, msisdnKey, userNameKey);
            List<CardNodeEntity> cns = (List<CardNodeEntity>) rpcResponse.getData();
            for (int i = 0; i < cns.size(); ) {
                CardNodeEntity cn = cns.get(i);
                cn.setId(++i);
            }

            List<CardNodeEntityWrapper> wrappers = cns.stream().map(p -> new CardNodeEntityWrapper(p)).collect(Collectors.toList());

            LinkedHashMap<String, String> names = new LinkedHashMap<>();
            names.put("id", "序号");
            names.put("appId", "平台ID");
            names.put("start", "号段起始");
            names.put("end", "号段结束");
            names.put("activeNum", "有效卡数目");
            names.put("pkgStr", "移动套餐");
            names.put("userPkgStr", "用户套餐");
            names.put("userPrice", "用户价格");
            names.put("userOpenDateStr", "激活日期");

            String filename = "号段_" + DateFormatUtils.format(new Date(), DateStyle.YYYYMMDDHHMMSS.getValue()) + "_" + user.getUSERNAME() + ".xls";
            downloadExcel(response, configAPI.getByCode(Const.UPLOAD_PATH).getValue(), filename, wrappers, names);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @return
     */
    public Map<String, String> getHC() {
        Subject currentUser = SecurityUtils.getSubject(); // shiro管理的session
        Session session = currentUser.getSession();
        return (Map<String, String>) session.getAttribute(Const.SESSION_QX);
    }


    /**
     * @param binder
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(format,
                true));
    }

}
